"use client"

import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Badge } from "@/components/ui/badge"
import { Trash2 } from "lucide-react"
import { useUser } from "@/lib/user-context"
import { useToast } from "@/components/ui/use-toast"

export default function WrongAnswersPage() {
  const [wrongAnswers, setWrongAnswers] = useState<any[]>([])
  const router = useRouter()
  const { user } = useUser()
  const { toast } = useToast()

  // 如果用户未登录，重定向到首页
  useEffect(() => {
    if (!user) {
      toast({
        title: "请先登录",
        description: "您需要登录后才能查看错题本",
        variant: "destructive",
      })
      router.push("/")
    } else {
      // 加载错题
      const storedWrongAnswers = JSON.parse(localStorage.getItem("wrongAnswers") || "[]")
      setWrongAnswers(storedWrongAnswers)
    }
  }, [user, router, toast])

  // 删除错题
  const deleteWrongAnswer = (id: number) => {
    const updatedWrongAnswers = wrongAnswers.filter((item) => item.id !== id)
    setWrongAnswers(updatedWrongAnswers)
    localStorage.setItem("wrongAnswers", JSON.stringify(updatedWrongAnswers))

    toast({
      title: "已删除",
      description: "该错题已从错题本中删除",
    })
  }

  // 清空错题本
  const clearWrongAnswers = () => {
    setWrongAnswers([])
    localStorage.setItem("wrongAnswers", JSON.stringify([]))

    toast({
      title: "已清空",
      description: "错题本已清空",
    })
  }

  // 按类型分组错题
  const vocabularyGrammarWrongs = wrongAnswers.filter((item) => !item.type || item.type === "vocabulary-grammar")
  const dialogueClozeWrongs = wrongAnswers.filter((item) => item.type === "dialogue-cloze")
  const readingWrongs = wrongAnswers.filter((item) => item.type === "reading")

  if (!user) {
    return null
  }

  return (
    <div className="container mx-auto px-4 py-8">
      <div className="flex justify-between items-center mb-8">
        <h1 className="text-2xl font-bold">错题本</h1>
        {wrongAnswers.length > 0 && (
          <Button variant="destructive" onClick={clearWrongAnswers}>
            清空错题本
          </Button>
        )}
      </div>

      {wrongAnswers.length === 0 ? (
        <Card>
          <CardContent className="flex flex-col items-center justify-center py-12">
            <p className="text-muted-foreground mb-4">您的错题本是空的</p>
            <Button onClick={() => router.push("/")}>开始练习</Button>
          </CardContent>
        </Card>
      ) : (
        <Tabs defaultValue="all">
          <TabsList className="mb-4">
            <TabsTrigger value="all">全部 ({wrongAnswers.length})</TabsTrigger>
            <TabsTrigger value="vocabulary-grammar">词汇与语法 ({vocabularyGrammarWrongs.length})</TabsTrigger>
            <TabsTrigger value="dialogue-cloze">情景对话与完形填空 ({dialogueClozeWrongs.length})</TabsTrigger>
            <TabsTrigger value="reading">阅读理解 ({readingWrongs.length})</TabsTrigger>
          </TabsList>

          <TabsContent value="all">
            <div className="space-y-4">
              {wrongAnswers.map((item) => (
                <WrongAnswerCard key={item.id} item={item} onDelete={() => deleteWrongAnswer(item.id)} />
              ))}
            </div>
          </TabsContent>

          <TabsContent value="vocabulary-grammar">
            <div className="space-y-4">
              {vocabularyGrammarWrongs.map((item) => (
                <WrongAnswerCard key={item.id} item={item} onDelete={() => deleteWrongAnswer(item.id)} />
              ))}
            </div>
          </TabsContent>

          <TabsContent value="dialogue-cloze">
            <div className="space-y-4">
              {dialogueClozeWrongs.map((item) => (
                <WrongAnswerCard key={item.id} item={item} onDelete={() => deleteWrongAnswer(item.id)} />
              ))}
            </div>
          </TabsContent>

          <TabsContent value="reading">
            <div className="space-y-4">
              {readingWrongs.map((item) => (
                <WrongAnswerCard key={item.id} item={item} onDelete={() => deleteWrongAnswer(item.id)} />
              ))}
            </div>
          </TabsContent>
        </Tabs>
      )}
    </div>
  )
}

function WrongAnswerCard({ item, onDelete }: { item: any; onDelete: () => void }) {
  return (
    <Card>
      <CardHeader className="flex flex-row items-start justify-between space-y-0 pb-2">
        <CardTitle className="text-sm font-medium">
          问题 {item.id}
          {item.type && (
            <Badge variant="outline" className="ml-2">
              {item.type === "dialogue-cloze" ? "情景对话" : item.type === "reading" ? "阅读理解" : "词汇语法"}
            </Badge>
          )}
        </CardTitle>
        <Button variant="ghost" size="sm" onClick={onDelete}>
          <Trash2 className="h-4 w-4" />
        </Button>
      </CardHeader>
      <CardContent>
        {item.passage && (
          <div className="mb-4 p-3 bg-muted rounded-md text-sm">
            <p className="font-medium mb-1">阅读文章:</p>
            <p>{item.passage}</p>
          </div>
        )}

        <p className="mb-2">{item.question}</p>

        <div className="grid gap-2 mb-4">
          {item.options &&
            item.options.map((option: any) => (
              <div
                key={option.id}
                className={`p-2 rounded-md text-sm ${
                  option.id === item.correctAnswer
                    ? "bg-green-100 dark:bg-green-900/20 border border-green-500"
                    : option.id === item.userAnswer
                      ? "bg-red-100 dark:bg-red-900/20 border border-red-500"
                      : "bg-muted"
                }`}
              >
                {option.id}. {option.text}
                {option.id === item.correctAnswer && (
                  <span className="ml-2 text-green-600 dark:text-green-400">✓ 正确答案</span>
                )}
                {option.id === item.userAnswer && option.id !== item.correctAnswer && (
                  <span className="ml-2 text-red-600 dark:text-red-400">✗ 您的答案</span>
                )}
              </div>
            ))}
        </div>

        {item.explanation && (
          <div className="p-3 bg-muted rounded-md text-sm">
            <p className="font-medium mb-1">解析:</p>
            <p>{item.explanation}</p>
          </div>
        )}
      </CardContent>
    </Card>
  )
}

